package com.jucai.pppeiyouclient.weidget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

import com.jucai.pppeiyouclient.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Kuky on 2017-04-26.
 */

public class GetVerTextView extends AppCompatTextView {

    private Timer timer;
    private TimerTask task;
    private int maxTime = 60;
    private int time = maxTime;
    private boolean isHandler = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (time != 0) {
                setText(time-- + "s");
            } else {
                timer.cancel();
                time = maxTime;
                setText("再次获取");
                isHandler = false;
                setBackgroundResource(R.drawable.shape_round_corner_orange_4dp);
            }
        }
    };


    public GetVerTextView(Context context) {
        super(context);
        initView(context);
    }

    public GetVerTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public GetVerTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        setBackgroundResource(R.drawable.shape_round_corner_orange_4dp);
        setTextColor(context.getResources().getColor(R.color.typeface_color));
        setText("获取验证码");
        setTextSize(12);
        setGravity(Gravity.CENTER);
        TextPaint paint = getPaint();
        int textLength = (int) paint.measureText(getText().toString());
        int margins = (int) (5 * (context.getResources().getDisplayMetrics().density) + 0.5f);
        setWidth(textLength + margins * 2);
        setPadding(margins, margins, margins, margins);
    }

    public void setHandler() {
        if (!isHandler) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
            timer.schedule(task, 0, 1000);
            isHandler = true;
            setBackgroundResource(R.drawable.shape_round_corner_gray_4dp);
        }
    }

    public boolean getIsHandler() {
        return isHandler;
    }
}
